package com.lagou.tomcat;

import org.apache.catalina.LifecycleException;
import org.apache.catalina.WebResourceRoot;
import org.apache.catalina.connector.Connector;
import org.apache.catalina.core.StandardContext;
import org.apache.catalina.startup.Tomcat;
import org.apache.catalina.webresources.DirResourceSet;
import org.apache.catalina.webresources.StandardRoot;

import javax.servlet.ServletException;
import java.io.File;

/**
 * tomcat启动类
 */
public class StartTomcat {

    private final static String protocol = "HTTP/1.1";

    public static void init(){
        try {
            // 创建Tomcat服务器对象
            Tomcat tomcat = new Tomcat();
            // 指定tomcat启动的端口号
            tomcat.setPort(8080);
            // 需指定资源路径，用于Tomcat扫描 META-INF/services/javax.servlet.MySpringServletContainerInitializer中配置的类
            StandardContext standardContext = (StandardContext) tomcat
                    .addWebapp("/", new File("src/main").getAbsolutePath());
            // 设置禁止重新载入属性为false
            standardContext.setReloadable(false);
            // 项目class文件所在地址
            File file = new File("target/classes");
            // 创建webResourceRoot对象
            WebResourceRoot webResourceRoot = new StandardRoot(standardContext);
            // Tomcat内部读取应用生成的class并执行
            webResourceRoot.addJarResources(new DirResourceSet(webResourceRoot,"/WEB-INF/classes",
                    file.getAbsolutePath(),"/"));
            // 启动Tomcat服务器
            tomcat.start();
            System.out.println("StartTomcat.init成功...");
            // 异步接收请求
            tomcat.getServer().await();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}
